package com.ainiyar.springweb.service.impl;

import com.ainiyar.springweb.common.result.ResultResponse;
import com.ainiyar.springweb.pojo.admin.dto.AdminDto;
import com.ainiyar.springweb.pojo.admin.dto.PageDto;
import com.ainiyar.springweb.pojo.admin.vo.AdminVo;
import com.ainiyar.springweb.pojo.entity.Admin;
import com.ainiyar.springweb.mapper.AdminMapper;
import com.ainiyar.springweb.service.AdminService;
import com.ainiyar.springweb.util.ToolsUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.If;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.ainiyar.springweb.pojo.entity.table.AdminTableDef.ADMIN;
import static com.ainiyar.springweb.pojo.entity.table.RoleTableDef.ROLE;

/**************************************
 * File Name : AdminServiceImpl
 * Created with : IntelliJ IDEA.
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time : 2024/2/4  12:28
 * Desc :管理员管理Service
 ***************************************/
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Resource
    private AdminMapper adminMapper;

    /**
     * 管理员列表
     *
     * @param pageDto  分页参数
     * @param adminDto 查询条件
     */
    @Override
    public ResultResponse<Object> lists(PageDto pageDto, AdminDto adminDto) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(ADMIN.DEFAULT_COLUMNS, ADMIN.IS_SUPPER.as("isDisabled"))
                .select(ROLE.NAME.as(AdminVo::getRoleName))
                .from(ADMIN)
                .leftJoin(ROLE).on(ADMIN.ROLE_ID.eq(ROLE.ID))
                .where(ADMIN.ACCOUNT.like(adminDto.getAccount(), If::hasText))
                .where(ADMIN.NICK_NAME.like(adminDto.getAccount(), If::hasText))
                .and(ADMIN.ROLE_ID.eq(adminDto.getRoleId(), If::notNull))
                .and(ADMIN.IS_ACCOUNT_NON_LOCKED.eq(adminDto.getStatus(), If::notNull))
                .and(ADMIN.PHONE.eq(adminDto.getPhone(), If::notNull))
                .orderBy(ADMIN.ID.desc());
        Page<AdminVo> adminPage = Page.of(pageDto.getPage(), pageDto.getPageSize());
        adminPage = adminMapper.paginateAs(adminPage, queryWrapper, AdminVo.class);

        return ResultResponse.pageList(adminPage.getRecords(), adminPage.getPageNumber(), adminPage.getPageSize(), adminPage.getTotalRow(), adminPage.getTotalPage());
    }

    /**
     * 根据账号查找管理员信息
     *
     * @param account 账号
     * @return Admin实体类
     */
    @Override
    public Admin findAdminByAccount(String account) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(ADMIN.DEFAULT_COLUMNS)
                .where(ADMIN.ACCOUNT.eq(account));
        return adminMapper.selectOneByQuery(queryWrapper);
    }

    /**
     * 根据id查找管理员信息
     *
     * @param id 管理员id
     * @return 管理员信息
     */
    @Override
    public Admin findAdminById(Long id) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(ADMIN.DEFAULT_COLUMNS)
                .where(ADMIN.ID.eq(id));
        return adminMapper.selectOneByQuery(queryWrapper);
    }

    /**
     * 保存新增，修改管理员信息
     *
     * @param admin_data 管理员实体类
     * @return true 成功  false 失败
     */
    @Override
    public boolean saveAddEditAdmin(Admin admin_data) {
        Admin admin = new Admin();
        //密码加密
        if (!ToolsUtil.isNullOrEmpty(admin_data.getPassword())) {
            PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String pass = passwordEncoder.encode(admin_data.getPassword());
            admin.setPassword(pass);
        }
        if (admin_data.getId() != null && admin_data.getId() != 0) {
            admin.setId(admin_data.getId());
        }
        admin.setAccount(admin_data.getAccount());
        admin.setNickName(admin_data.getNickName());
        admin.setPhone(admin_data.getPhone());
        admin.setEMail(admin_data.getEMail());
        admin.setRoleId(admin_data.getRoleId());
        admin.setSex(admin_data.getSex());
        admin.setType(admin_data.getType());
        admin.setAvatar(admin_data.getAvatar());
        admin.setAccountNonLocked(admin_data.isAccountNonLocked());
        return adminMapper.insertOrUpdateSelective(admin) > 0;
    }

    /**
     * 检查管理员名称(账号是否存在)
     *
     * @param account  管理员名称
     * @param admin_id 管理员id
     * @return true:管理员名称存在  false:管理员名称不存在
     */
    @Override
    public boolean checkAccount(String account, Long admin_id) {
        Map<String, Object> condition = Map.of("account", account.trim());
        Admin admin = adminMapper.selectOneByMap(condition);
        return admin != null && !admin.getId().equals(admin_id);
    }

    /**
     * 删除管理员
     *
     * @param id 管理员id
     * @return boolean
     */
    @Override
    public boolean deleteAdmin(Long id) {
        return adminMapper.deleteById(id) > 0;
    }

    /**
     * 批量删除管理员
     *
     * @param ids 所需批量删除数据的id
     * @return boolean
     */
    @Override
    public boolean batchDelete(Long[] ids) {
        //1.批了删除中去除超级超级管理员
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(ADMIN.ID)
                .where(ADMIN.ID.in((Object) ids))
                .and(ADMIN.IS_SUPPER.ne(1));
        List<Object> admin_ids = adminMapper.selectObjectListByQuery(queryWrapper);
        Long[] ids_array = new Long[admin_ids.size()];
        int index = 0;
        for (Object element : admin_ids) {
            ids_array[index++] = (Long) element;
        }
        //2.批量删除
        return adminMapper.deleteBatchByIds(Arrays.asList(ids_array)) > 0;
    }

    /**
     * 根据角色id获取管理员
     *
     * @param role_id 角色id
     * @return Admin
     */
    @Override
    public List<Admin> findAdminByRoleId(Long role_id) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(ADMIN.DEFAULT_COLUMNS)
                .where(ADMIN.ROLE_ID.eq(role_id));
        return adminMapper.selectListByQuery(queryWrapper);
    }
}

